package vip.rpai.notepad

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import org.jetbrains.anko.alert
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.startActivityForResult
import vip.rpai.notepad.databinding.ActivityMainBinding

//梦开始的地方
class MainActivity : AppCompatActivity() {

    private lateinit var binding: ActivityMainBinding//视图控件绑定
    private val leSS = LeSS(this)//数据操作实体类

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        initListView()//初始化ListView
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        Log.d("Lexuss", "返回码"+requestCode)
        when (requestCode) {
            LeSS.requestCodeAddInfoActivity -> {
                mainTipTV2()//隐藏提醒
                leSS.showData()
            }
        }
        super.onActivityResult(requestCode, resultCode, data)


    }

    //初始化视图及数据
    private fun initListView() {
        binding.mainInfoLV.adapter = leSS.fruitAdapter//指定适配器
        leSS.initData()//初始化列表数据并显示到界面
        mainTipTV2()//提示显隐
        //点击监听器
        binding.mainInfoLV.setOnItemClickListener { _, _, position, _ -> itemClick(position) }
        //长按监听器
        binding.mainInfoLV.setOnItemLongClickListener { _, _, position, _ -> itemLongClick(position) }

    }

    //判断显隐提示
    private fun mainTipTV2() {
        binding.mainTipTV2.visibility = if (LeSS.dataList.size > 0) View.GONE else View.VISIBLE
    }

    //列表项点击事件
    private fun itemClick(position: Int) {
        //点击列表项启动新页面
        startActivity<AddInfoActivity>("position" to position)
    }

    //列表项长按事件
    private fun itemLongClick(position: Int): Boolean {
        alert(getString(R.string.tipDeleteItemMessage), getString(R.string.tipDeleteItemTitle)) {
            positiveButton(getString(R.string.tipOK)) {
                leSS.reMoveData(arrayListOf(position))
                mainTipTV2()//确认是否显示提示
            }
            negativeButton(getString(R.string.tipNO)) {}
        }.show()
        return true
    }

    //新增按钮点击事件
    fun mainAddItemBTOnClick(view: View) {
        view.id
        startActivityForResult<AddInfoActivity>(LeSS.requestCodeAddInfoActivity)
    }
}